package com.ll.gulimall.serach.service.impl;

import com.alibaba.fastjson.JSON;
import com.ll.common.constant.ElasticConstant;
import com.ll.common.exception.BizCodeEnume;
import com.ll.common.to.es.SkuEsModel;
import com.ll.gulimall.serach.config.GulimallElasticSearchConfig;
import com.ll.gulimall.serach.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    RestHighLevelClient client;

    @Override
    public Boolean productUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 创建批量操作对象
        BulkRequest bulkRequest = new BulkRequest();
        //创建需要批量操作的请求
        for (SkuEsModel sku : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(ElasticConstant.PRODUCT_INDEX);
            indexRequest.id(sku.getSkuId().toString());
            String skuString = JSON.toJSONString(sku);
            indexRequest.source(skuString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        //执行是否失败
        boolean b = bulk.hasFailures();

        //TODO 如果有一条数据索引失败则需要处理
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            // TODO 在这里需要得到错误的数据Id方便后期操作
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架成功:{}返回数据",collect);
        return b;

    }
}
